export const calculate = (expression) => {
	if(!expression) return 0
    expression = expression.replace(/\s+/g, '');

    // 处理末尾多余的运算符
    if (/[\+\-\*\/]$/.test(expression)) {
        expression = expression.slice(0, -1);
    }

    // 基础运算
    const numbers = expression.split(/[\+\-\*\/]/);
    const operators = expression.replace(/[0-9\.]+/g, '').split('');

    // 处理乘除
    for (let i = 0; i < operators.length; i++) {
        if (operators[i] === '*') {
            numbers[i] = parseFloat(numbers[i]) * parseFloat(numbers[i + 1]);
            numbers.splice(i + 1, 1);
            operators.splice(i, 1);
            i--;
        } else if (operators[i] === '/') {
            numbers[i] = parseFloat(numbers[i]) / parseFloat(numbers[i + 1]);
            numbers.splice(i + 1, 1);
            operators.splice(i, 1);
            i--;
        }
    }

    // 处理加减
    let result = parseFloat(numbers[0]);
    for (let i = 0; i < operators.length; i++) {
        if (operators[i] === '+') {
            result += parseFloat(numbers[i + 1]);
        } else if (operators[i] === '-') {
            result -= parseFloat(numbers[i + 1]);
        }
    }

    return result;
}

export const formatExpression = (expression) => {
    // 清除空格
    expression = expression.replace(/\s+/g, '');

    // 替换多个连续的小数点为一个
    expression = expression.replace(/(\.\.+)/g, '.');

    // 去除小数点后有符号的点
    expression = expression.replace(/(\.\d+)(?=[+\-*\/])/g, '$1').replace(/\.(?=[+\-*\/])/g, '');

    // 保留合法的小数和运算符
    expression = expression
        .replace(/(\d+)\.(\d+)\./g, '$1.$2')  // 处理多个小数点
        .replace(/([+\-*\/]){2,}/g, '$1')      // 将多个运算符替换为一个
        .replace(/^([+\-*\/]+)/g, '');         // 去除开头的运算符

    return expression;
}

